package ru.kreda.webapp.server;

import java.util.ArrayList;
import java.util.List;

import net.customware.gwt.dispatch.server.ExecutionContext;
import ru.kreda.webapp.client.invocation.OrderListRequestAction;
import ru.kreda.webapp.client.invocation.OrderListRequestResult;
import ru.kreda.webapp.shared.model.OrderListFilterModel;
import ru.kreda.webapp.shared.model.OrderModel;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;

public class OrderListCommandHandler extends BaseActionHandler<OrderListRequestAction, OrderListRequestResult> {

	private OrderModel getOrder(Long id) {
		OrderModel model = new OrderModel();
		model.set(OrderModel.ID, id);
		model.set(OrderModel.CLIENT_ID, id);
		model.set(OrderModel.CLIENT_FIO, "Петров Петр Петрович (" + id + ")");
		model.set(OrderModel.ACCOUNT, (long) 10000*Math.random());
		model.set(OrderModel.FROM, "01.01.2000");
		model.set(OrderModel.TO, "01.01.2000");
		model.set(OrderModel.INN, "237834628341");
		return model;
	}

	static int ALL_COUNT = 444;

	
	@Override
	protected OrderListRequestResult executeAction(OrderListRequestAction action, ExecutionContext context) throws Exception {
		OrderListFilterModel filter = action.getFilter();
		List<OrderModel> list = new ArrayList<OrderModel>();
		for (int i = filter.getOffset(); i < filter.getOffset()+filter.getLimit(); i++) {
			if (i == 77) {
				throw new NullPointerException("test");
			}
			list.add(getOrder((long) i));
		}
		return new OrderListRequestResult(new BasePagingLoadResult<OrderModel>(list, filter.getOffset(), ALL_COUNT));
	}

	@Override
	public Class<OrderListRequestAction> getActionType() {
		return OrderListRequestAction.class;
	}

}
